package org.usmile.algorithms.learn.string;

public class BF {
    public int indexOf(String mainStr, String patternStr) {
        if (mainStr == null || patternStr == null) {
            return -1;
        }

        int m = mainStr.length();
        int n = patternStr.length();
        if (n > m) {
            return -1;
        }

        for (int i = 0; i < m; i++) {
            int k = i;
            for (int j = 0; j < n; j++) {
                if (patternStr.charAt(j) == mainStr.charAt(k)) {
                    k++;
                    if (j == n - 1) {
                        return j;
                    }
                } else {
                    break;
                }
            }
        }

        return -1;
    }

    public int indexOf1(String mainStr, String patternStr) {
        if (mainStr == null || patternStr == null) {
            return -1;
        }

        int m = mainStr.length();
        int n = patternStr.length();
        if (n > m) {
            return -1;
        }

        char first = patternStr.charAt(0);
        for (int i = 0; i < m; i++) {
            if (mainStr.charAt(i) != first) {
                while (i < m && mainStr.charAt(i) != first) {
                    i++;
                }
            }

            if (i < m) {
                int k = i + 1;
                for (int j = 1; j < n && k < m; j++, k++) {
                    if (mainStr.charAt(k) == patternStr.charAt(j)) {
                        if (j == n - 1) {
                            return j;
                        }
                    }
                }
            }
        }

        return -1;
    }
}
